//
//  WFStatusDAL.swift
//  WangFangWeiBo
//
//  Created by 王方 on 16/7/23.
//  Copyright © 2016年 wf. All rights reserved.
//

import UIKit

let MAXTime:Double = -(60 * 60 * 24 * 7)

//数据库访问层
class WFStatusDAL: NSObject {
    // MARK:  -  加载数据
    class func loadData(maxId: Int64, sinceId: Int64, callBack: (statuses: [[String: AnyObject]])->()) {
        //1.检查本地是否有缓存数据
        let result = checkCacheData(maxId,sinceId: sinceId)
        
        //2.如果有缓存数据则返回缓存数据
        if result.count > 0 {
            callBack(statuses: result)
            return
        }
        //3.如果没有缓存数据就从网络加载
         let tempArray = [[String: AnyObject]]()
        WFNetWorkTools.sharedTools.loadStatus(maxId, sinceId: sinceId) { (response, error) -> () in
            if error != nil {
                print(error)
                callBack(statuses: tempArray)
                return
            }
            
            //代码执行到此是成功的回调
            guard let dic = response as? [String:AnyObject] else {
                print("不是一个正确的字典")
                callBack(statuses: tempArray)
                return
            }
            //代码执行到此,字典格式也是正确的
            guard let statusDicArray = dic["statuses"] as? [[String: AnyObject]] else {
                print("不是一个正确的字典格式")
                callBack(statuses: tempArray)
                return
            }
            //  4.网络加载后的数据缓存到本地
            WFStatusDAL.cacheData(statusDicArray)
            
            // 5.数据缓存成功后,返回网络加载后的数据
            callBack(statuses: statusDicArray)

        }
    }
    
    
    
 // MARK:  -  通过maxid和sinceid去本地查询数据
    class func checkCacheData(maxId:Int64,sinceId:Int64)->[[String:AnyObject]]{
        
        var sql = "SELECT statusid, status, userid from statuses\n"
        
        if maxId > 0{
            sql += "WHERE STATUS < \(maxId) "
        }else{
            sql += "WHERE STATUS > \(sinceId) "
        }
        //拼接userid
        sql += "and userid = \(WFUserAccountViewModel.sharedUserAccount.userAccount!.uid) "
        //排序方式
        sql += "order by statusid desc "
        //每页加载20条数据
        sql += "limit 20 "
        //查询本地数据
        let result = SqliteManager.manager.queryResultSet(sql)
        var tempArray = [[String: AnyObject]]()
        for value in result {
            //  获取微博字典二进制数据
            let statusData = value["status"]! as! NSData
            //  取到微博缓存数据的字典
            let statusDic = try! NSJSONSerialization.JSONObjectWithData(statusData, options: []) as! [String: AnyObject]
            tempArray.append(statusDic)
        }
        return tempArray
    }
    
    // MARK:  - 清空缓存
    class func clearCacheData() {
        let dt = NSDateFormatter()
        dt.dateFormat = "yyyy-MM-dd HH:mm:ss"
        dt.locale = NSLocale(localeIdentifier: "en_US")
        let time = NSDate().dateByAddingTimeInterval(MAXTime)
        //获取时间字符串
        let timeStr = dt.stringFromDate(time)
        let sql = "DELETE FROM STATUS WHERE TIME < '\(timeStr)'"
        //执行
        SqliteManager.manager.queue.inDatabase { (db) -> Void in
             let result = db.executeUpdate(sql, withArgumentsInArray: nil)
            if result {
                print("缓存数据删除成功,影响了\(db.changes())条数据")
            }else{
                print("缓存数据删除失败")
            }
        }    }
    
    // MARK:  - 缓存服务端返回给我们的数组字典
    class func cacheData(statuses:[[String:AnyObject]]) {
        let sql = "INSERT INTO STATUSES(STATUSID, STATUS, USERID) VALUES(?, ?, ?)"
        //获取用户id
        let userid = WFUserAccountViewModel.sharedUserAccount.userAccount!.uid
        SqliteManager.manager.queue.inTransaction { (db, rollBack) -> Void in
            for status in statuses {
                let statusid = status["id"]
                let statusData = try! NSJSONSerialization.dataWithJSONObject(status, options: [])
                let result = db.executeUpdate(sql, withArgumentsInArray: [statusid!,statusData,"\(userid)"])
                if result == false {
                    rollBack.memory = true
                    break
                }
            }
        }
    }
}
